//
//  AppDelegate.m
//  YunDongAdmin
//
//  Created by lqq on 2018/9/4.
//  Copyright © 2018年 cloudfighting.com. All rights reserved.
//

#import "AppDelegate.h"
#import "MainTabBarController.h"
#import "BaseNavgationController.h"
#import "LoginViewController.h"
#import "I_APPManager.h"
#import <UMPush/UMessage.h>
#import <UMCommon/UMCommon.h>
#import <UMShare/UMShare.h>
#import "SystemAlertViewController.h"
#import "GuideViewController.h"
#import "AdvertViewController.h"
#import "CompletionAccountInfoController.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //上传设备信息
    [I_APPManager uploadDeviceInfo];
    
    //注册通知
    [self registerForRemoteNotificationWithLaunchOptions:launchOptions];
    //统计
    [self configAnalytics];
    
    //分享
    [self configUSharePlatforms];

    
    //设置Web的UserAgent
    [self setWebUserAgent];
    
    //检测更新
    [self checkAppUpdate];
    
    //配置app启动逻辑
    [self configLaunchLogic];
    
    
    return YES;
}


#pragma mark 启动逻辑
- (void)configLaunchLogic
{
//    BOOL notFirstUseApp = [[NSUserDefaults standardUserDefaults] boolForKey:kNotFirstUseApp];
//    if (!notFirstUseApp) {
//        //第一次启动
//        GuideViewController *guideVC = [[GuideViewController alloc] initWithNibName:@"GuideViewController" bundle:nil];
//        self.window.rootViewController = guideVC;
//        __weak __typeof (guideVC)weakGuideVC = guideVC;
//        WeakSelf(self);
//        guideVC.finishBlock = ^{
//            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kNotFirstUseApp];
//            UIViewController *toVC;
//            if (RI.isLogin) {
//                if (RI.account.brandName) {
//                    MainTabBarController *mainTabBarVC = [[MainTabBarController alloc] init];
//                    toVC = mainTabBarVC;
//                } else {
//                    CompletionAccountInfoController *vc = [CompletionAccountInfoController controller];
//                    BaseNavgationController *navVC = [[BaseNavgationController alloc] initWithRootViewController:vc];
//                    toVC = navVC;
//                }
//
//            } else {
//                UIStoryboard *accountStoryBoard = [UIStoryboard storyboardWithName:@"Account" bundle:nil];
//                BaseNavgationController *loginNav = [accountStoryBoard instantiateInitialViewController];
//                toVC = loginNav;
//            }
//            [UIView transitionFromView:weakGuideVC.view toView:toVC.view duration:0.5 options:UIViewAnimationOptionTransitionCrossDissolve completion:^(BOOL finished) {
//                weakself.window.rootViewController = toVC;
//            }];
//        };
//    } else {
        if (RI.isLogin) {//已登录
            if (RI.account.brandName) {
#ifdef DEBUG
                MainTabBarController *mainTabBarVC = [[MainTabBarController alloc] init];
                self.window.rootViewController = mainTabBarVC;
#else
                //广告页
                AdvertViewController *advertVC = [AdvertViewController controller];
                self.window.rootViewController = advertVC;
                __weak __typeof(advertVC) weakAdvertVC = advertVC;
                WeakSelf(self);
                advertVC.overleapBlock = ^{
                    MainTabBarController *mainTabBarVC = [[MainTabBarController alloc] init];
                    [UIView transitionFromView:weakAdvertVC.view toView:mainTabBarVC.view duration:0.5 options:UIViewAnimationOptionTransitionCrossDissolve completion:^(BOOL finished) {
                        weakself.window.rootViewController = mainTabBarVC;
                        
                    }];
                    
                };
                
                advertVC.clickedAdvertBlock = ^(M_Advert *advert) {
                    MainTabBarController *mainTabBarVC = [[MainTabBarController alloc] init];
                    [UIView transitionFromView:weakAdvertVC.view toView:mainTabBarVC.view duration:0.5 options:UIViewAnimationOptionTransitionCrossDissolve completion:^(BOOL finished) {
                        weakself.window.rootViewController = mainTabBarVC;
                        //跳转广告
                        [weakself jumpAdvert:advert];
                    }];
                };
                
#endif
            } else {
                CompletionAccountInfoController *vc = [CompletionAccountInfoController controller];
                BaseNavgationController *navVC = [[BaseNavgationController alloc] initWithRootViewController:vc];
                self.window.rootViewController = navVC;
            }

            
        } else {//未登录，不打广告
            UIStoryboard *accountStoryBoard = [UIStoryboard storyboardWithName:@"Account" bundle:nil];
            BaseNavgationController *loginNav = [accountStoryBoard instantiateInitialViewController];
            self.window.rootViewController = loginNav;
        }
//    }
    
}


#pragma mark 推送
/**
 注册远程推送
 */
- (void)registerForRemoteNotificationWithLaunchOptions:(NSDictionary *)launchOptions
{
    // Push组件基本功能配置
    UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
    entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionSound|UMessageAuthorizationOptionAlert;
    if (@available(iOS 10.0, *)) {
        [UNUserNotificationCenter currentNotificationCenter].delegate=self;
    } else {
        // Fallback on earlier versions
    }
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
        }else{
        }
    }];
    
    //设置是否允许SDK自动清空角标
    [UMessage setBadgeClear:YES];
    
    //设置是否允许SDK当应用在前台运行收到Push时弹出Alert框
    [UMessage setAutoAlert:NO];
}



/**
 注册deviceToken成功
 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken
{
    // 1.2.7版本开始不需要用户再手动注册devicetoken，SDK会自动注册
    //    [UMessage registerDeviceToken:deviceToken];
    NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                        stringByReplacingOccurrencesOfString: @">" withString: @""]
                       stringByReplacingOccurrencesOfString: @" " withString: @""];
    NSLog(@"token--%@",token);
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:kPushTokenKey];
    [I_APPManager upLoadPushToken];
}

//iOS10以下使用这两个方法接收通知
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [UMessage setAutoAlert:NO];
    if([[[UIDevice currentDevice] systemVersion]intValue] < 10){
        [UMessage didReceiveRemoteNotification:userInfo];
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [UMessage setAutoAlert:NO];
        //应用处于前台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
    }else{
        //应用处于前台时的本地推送接受
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
    }else{
        //应用处于后台时的本地推送接受
    }
    
}
#pragma mark 分享
- (void)configUSharePlatforms
{
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx43b25ae94b323fe2" appSecret:@"098164dbbb3971d122ec8ca9029a8ef2" redirectURL:@"http://mobile.umeng.com/social"];
#ifdef DEBUG
    //打开日志调试
    [[UMSocialManager defaultManager] openLog:YES];
#else
    [[UMSocialManager defaultManager] openLog:NO];
    
#endif
}
// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

#pragma mark 统计
- (void)configAnalytics
{
    [UMConfigure initWithAppkey:@"5b961fb28f4a9d2fe9000085" channel:@"App Store"];
    
#ifdef DEBUG
    //打开日志调试
    [UMConfigure setLogEnabled:YES];
#else
    [UMConfigure setLogEnabled:NO];
    
#endif
    
}


#pragma mark 检测更新
- (void)checkAppUpdate
{
    //检测APP更新
    [I_APPManager checkAPPUpdateSuccess:^(NSDictionary *result) {
        BOOL updateStatus = [[result safeObjectForKey:@"updateStatus"] boolValue];
        if (updateStatus) {
            NSString *downUrl = [result safeObjectForKey:@"downUrl"];
            downUrl = [downUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            //            downUrl = @"itms-apps://itunes.apple.com/cn/app/id1399471514?mt=8";
            BOOL forceUpdate = [[result safeObjectForKey:@"forceUpdate"] boolValue];
            NSString *content = [result safeObjectForKey:@"content"];
            if (forceUpdate) {
                UIStoryboard *mainStorryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                BaseNavgationController *loginNav = [mainStorryboard instantiateInitialViewController];
                self.window.rootViewController = loginNav;
                
                [SystemAlertViewController alertViewControllerWithTitle:@"发现新版本，请更新" message:content cancleButtonTitle:nil commitButtonTitle:@"前往更新" cancleBlock:^{
                    
                } commitBlock:^{
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:downUrl]];
                }];
                
                
                
            } else {
                CGFloat delayTime = [[result safeObjectForKey:@"delayTime"] floatValue];
                if (delayTime < 5) {
                    delayTime = 5;
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SystemAlertViewController alertViewControllerWithTitle:@"发现新版本，是否更新？" message:content cancleButtonTitle:@"取消" commitButtonTitle:@"前往更新" cancleBlock:^{
                        
                    } commitBlock:^{
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:downUrl]];
                    }];
                });
            }
        }
    } failure:^(NSError *error) {
        
        
    }];
}

#pragma mark 设置Web的UserAgent
- (void)setWebUserAgent
{
    //设置web UserAgent
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *newUserAgent = [userAgent stringByAppendingString:@" cloudfighting"];//自定义需要拼接的字符串
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    
}


#pragma mark Pravite
- (void)jumpAdvert:(M_Advert *)advert
{
    if (advert.jumpTarget.length == 0) {
        return;
    }
    UITabBarController *mainRoot = (UITabBarController *)self.window.rootViewController;
    UIViewController *currentIndexVC = [mainRoot.viewControllers safeObjectAtIndex:mainRoot.selectedIndex];
    UINavigationController *navVC ;
    if ([currentIndexVC isKindOfClass:[UINavigationController class]]) {
        navVC = (UINavigationController *)currentIndexVC;
    } else {
        mainRoot.selectedIndex = 0;
        navVC = [mainRoot.viewControllers safeObjectAtIndex:mainRoot.selectedIndex];
    }
    switch (advert.jumpType) {
        case JumpType_H5:
        {
            YDWebViewController *webVC = [YDWebViewController controllerWithUrl:advert.jumpTarget];
            [navVC pushViewController:webVC animated:YES];
        }
            break;
            
        default:
            break;
    }
}


- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // app启动或者app从后台进入前台都会调用这个方法
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // app从后台进入前台都会调用这个方法
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ApplicationWillEnterForeground" object:nil];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"YunDongAdmin"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end
